<template>
  <div class="home">
    <div class="wrap">
      <ul class="nav">
        <li
          v-for="(item, index) in fenlei"
          :key="item._id"
          @click="change(item._id, index)"
          :class="{ active: flag == index }"
        >
          {{ item.title }}
        </li>
      </ul>
    </div>
    <!-- 商品分类 -->

    <ul class="list">
      <li v-for="item in result" :key="item._id" @click="gotodetail(item)">
        <img :src="item.pic" alt="" />
        <h5>{{ item.title }}</h5>
      </li>
    </ul>
    <!-- 商品列表 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      fenlei: [],
      //分类数据
      list: [],
      //所有商品数据
      result: [],
      //筛选结果数据
      flag: 0,
    };
  },
  created() {
    this.$axios.get("fenlei.json").then((res) => {
      console.log(res);
      this.fenlei = res.data.result;
    });
    //进入页面请求分类数据
    this.getlist();
    //进入页面请求列表所有的数据
  },
  methods: {
    getlist() {
      this.$axios.get("list.json").then((res) => {
        this.list = res.data.result;
        this.change("59f1e1ada1da8b15d42234e9", 0);
        //拿到数据之后进行一次查询 默认的值 是 第一个商品分类的id
      });
    },
    //请求所有列表数据
    change(id, index) {
      this.flag = index;
      this.result = this.list.filter((item) => {
        return item.cid == id;
      });
    },
    //根据你点的分类筛选list中cid跟当前点的分类id一样的数据

    gotodetail(item) {
      this.$router.push({ path: "/detail", query: { obj: item } });
    },
    //跳转详情页
  },
};
</script>
<style lang="scss">
.wrap {
  width: 100%;
  overflow: scroll;
  ul {
    display: flex;
    li {
      width: 80px;
      height: 40px;
      border: 1px solid #ccc;
      line-height: 40px;
      text-align: center;
      flex-shrink: 0;
      //让元素不缩小
    }
  }
}

.list {
  display: flex;
  flex-wrap: wrap;
  > li {
    width: 50%;
    text-align: center;
    border: 1px solid #ccc;
    box-sizing: border-box;
    padding-top: 20px;
    margin-top: 20px;
    img {
      width: 80%;
    }
  }
}
.active {
  color: chocolate;
}
</style>
